package com.shaoshaohuo.app.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.navi.model.NaviLatLng;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.entity.DriverEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.ui.MyLocationActivity;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/6/25.
 */

public class CarDriverFramgment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private int pos;
    private Myadapter myadapter;
    private Handler handler = new Handler();

    /**
     * 定位相关
     *
     * @param postion
     * @return
     */
    private double latitude;
    private double longitude;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation.getErrorCode() == 0) {
                //纬度
                latitude = aMapLocation.getLatitude();
                //经度
                longitude = aMapLocation.getLongitude();
                Toast.makeText(getContext(), "定位成功", Toast.LENGTH_LONG).show();
                Log.e("TAG", "onLocationChanged: 成功定位感人= = =");
                if (CarDriverFramgment.this.longitude > 0 && CarDriverFramgment.this.latitude > 0) {
                    NaviLatLng end = new NaviLatLng(Double.valueOf(startlatitude), Double.valueOf(startlongitude));
                    NaviLatLng start = new NaviLatLng( CarDriverFramgment.this.latitude,CarDriverFramgment.this.longitude);
                    Intent intent = new Intent();
                    intent.putExtra("start", start);
                    intent.putExtra("end", end);
                    intent.putExtra("orderid",orderid);
                    intent.setClass(getContext(), MyLocationActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.toast("请等待定位完成");
                }
            }
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
//            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    };
    private String startlatitude;
    private String startlongitude;
    private SwipeRefreshLayout swp;
    private String orderid;

    public static CarDriverFramgment newInstance(int postion) {

        Bundle args = new Bundle();
        args.putInt("pos", postion);
        CarDriverFramgment fragment = new CarDriverFramgment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View inflate = inflater.inflate(R.layout.fragment_cardriver, null);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLocationClient = new AMapLocationClient(getContext());
////设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        mLocationOption.setInterval(1000);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//        mLocationOption.setOnceLocationLatest(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        /**
         * 定位、=============================
         */
        Bundle arguments = getArguments();
        pos = arguments.getInt("pos");
        ListView frg_cardriver_list = (ListView) view.findViewById(R.id.frg_cardriver_list);
        myadapter = new Myadapter();
        frg_cardriver_list.setAdapter(myadapter);
        swp = (SwipeRefreshLayout) view.findViewById(R.id.swp);
        swp.setOnRefreshListener(this);
        network();
        frg_cardriver_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                CarDriverFramgment.Myadapter adapter = (Myadapter) parent.getAdapter();
                List<DriverEntity.DataBean> getdate = adapter.getdate();
                DriverEntity.DataBean dataBean = getdate.get(position);
                String orderid = dataBean.getOrderid();
                intent.putExtra("orderid", orderid);
                intent.putExtra("pos", pos);
                intent.setClass(getContext(), CaeDeltaActivirt.class);
                startActivity(intent);
            }
        });
    }

    private void network() {
        ShopHttpConfig.driverqurey(getContext(), (pos + 1) + "", new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                DriverEntity driverEntity = (DriverEntity) o;
                final List<DriverEntity.DataBean> data = driverEntity.getData();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        myadapter.setdate(data);
                    }
                });
            }
        }, DriverEntity.class);
    }

    @Override
    public void onRefresh() {
        network();
        swp.setRefreshing(false);
    }

    class Myadapter extends BaseAdapter implements View.OnClickListener {
        private List<DriverEntity.DataBean> list = new ArrayList<>();

        public void setdate(List<DriverEntity.DataBean> list) {
            this.list = list;
            notifyDataSetChanged();
        }

        public List<DriverEntity.DataBean> getdate() {
            return list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Myholder myholder;
            if (convertView == null) {
                myholder = new Myholder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.cardriverlistitem, null);
                myholder.tv_bookPhone = (TextView) convertView.findViewById(R.id.bookPhone);
                myholder.tv_orderid = (TextView) convertView.findViewById(R.id.orderid);
                myholder.tv_preTime = (TextView) convertView.findViewById(R.id.preTime);
                myholder.tv_reDetails = (TextView) convertView.findViewById(R.id.reDetails);
                myholder.tv_reName = (TextView) convertView.findViewById(R.id.reName);
                myholder.tv_rePhone = (TextView) convertView.findViewById(R.id.rePhone);
                myholder.iv_map = (ImageView) convertView.findViewById(R.id.iv_map);
                convertView.setTag(myholder);
            } else {
                myholder = (Myholder) convertView.getTag();
            }
            DriverEntity.DataBean dataBean = list.get(position);
            String bookPhone = dataBean.getBookPhone();
            String orderid = dataBean.getOrderid();
            String doorDetauls = dataBean.getDoorDetauls();
            String preTime = dataBean.getPreTime();
            String reName = dataBean.getReName();
            String reDetails = dataBean.getReDetails();
            String rePhone = dataBean.getRePhone();
            myholder.tv_rePhone.setText("电话号码：" + rePhone);
            myholder.tv_reName.setText("姓名：" + reName);
            myholder.tv_reDetails.setText("地址：" + reDetails + doorDetauls);
            myholder.tv_bookPhone.setText("送单人员号码：" + bookPhone);
            myholder.tv_preTime.setText("预计配送时间：" + preTime);
            myholder.tv_orderid.setText("订单号：" + orderid);
            myholder.iv_map.setTag(position);
            myholder.iv_map.setOnClickListener(this);
            return convertView;
        }

        @Override
        public void onClick(View v) {
            int tag = (int) v.getTag();
            DriverEntity.DataBean dataBean = list.get(tag);
            startlatitude = dataBean.getLatitude();
            startlongitude = dataBean.getLongitude();
            orderid = dataBean.getOrderid();
            mLocationClient.startLocation();
        }

        class Myholder {
            TextView tv_orderid,
                    tv_reName,
                    tv_rePhone, tv_reDetails, tv_bookPhone, tv_preTime;
            ImageView iv_map;

        }
    }
}
